package org.rslai.autotest.core.page.impl;

import java.util.Iterator;
import java.util.Set;

import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.WebDriver;
import org.rslai.autotest.core.page.AbstractHelper;
import org.rslai.autotest.core.page.Frame;
import org.rslai.autotest.core.page.Window;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * Window处理方法实现<br>
 * 提供切换到指定窗体、返回前一个窗体、关闭指定窗体等方法
 * @author rslai
 */
public class WindowImpl extends AbstractHelper implements Window{
	@Autowired
	private Frame frame;

	@Value("${webdriverwait.timeout}")
	private int webdriverwaitTimeout; // 使用wait查找对象的超时时间

	public boolean switchToWindow(String titleOrUrl) {
		return switchToWindow(titleOrUrl, webdriverwaitTimeout);
	}

	public boolean switchToWindow(String titleOrUrl, int waitTimeout) {
		this.frame.initCurrentFrame(); // 执行切换窗体前，初始化当前 Frame（此种方式耦合性太强，不过没办法目前只想到此种方式）

		String currentWindow;
		try {
			currentWindow = this.driver().getWindowHandle(); // 得到当前窗口的句柄
		} catch (NoSuchWindowException ex) {
			currentWindow = null;
		}

		for (int i = 0; i < waitTimeout; i++) {
			Set<String> handles = this.driver().getWindowHandles(); // 得到所有窗口的句柄
			Iterator<String> it = handles.iterator();
			while (it.hasNext()) {
				String handle = it.next();
				if (currentWindow != null && currentWindow.equals(handle)) {
					continue;
				}
				WebDriver window = this.driver().switchTo().window(handle);
				if (window.getTitle().indexOf(titleOrUrl) != -1 || window.getCurrentUrl().indexOf(titleOrUrl) != -1) {
					this.driver().switchTo().window(handle);
					return true;
				}
			}
			super.sleep(1);
		}

		throw new NoSuchWindowException("无法切换到指定窗体（经过 " + waitTimeout + " 秒后仍未找到窗体title或url中包含“" + titleOrUrl + "”的窗体）。");
	}

	public boolean closeWindow(String titleOrUrl) {
		return this.closeWindow(titleOrUrl, webdriverwaitTimeout);
	}

	public boolean closeWindow(String titleOrUrl, int waitTimeout) {
		this.frame.initCurrentFrame(); // 执行关闭窗体前，初始化当前 Frame（此种方式耦合性太强，不过没办法目前只想到此种方式）

		String currentWindow;
		try {
			currentWindow = this.driver().getWindowHandle(); // 得到当前窗口的句柄
		} catch (NoSuchWindowException ex) {
			currentWindow = null;
		}

		for (int i = 0; i < waitTimeout; i++) {
			Set<String> handles = this.driver().getWindowHandles(); // 得到所有窗口的句柄
			Iterator<String> it = handles.iterator();
			while (it.hasNext()) {
				String handle = it.next();
				WebDriver window = this.driver().switchTo().window(handle);
				if (window.getTitle().indexOf(titleOrUrl)!=-1 || window.getCurrentUrl().indexOf(titleOrUrl)!=-1) {
					window.close();
					if (currentWindow != null && !currentWindow.equals(handle)) {
						this.driver().switchTo().window(currentWindow); // 切换回当前窗口
					}
					return true;
				}
			}
			super.sleep(1);
		}

		throw new NoSuchWindowException("无法关闭指定窗体（经过 " + waitTimeout + " 秒后仍未找到窗体title或url中包含“" + titleOrUrl + "”的窗体）。");
	}

}
